package com.example.demo.controller;

import com.example.demo.until.AliyunOSSUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lightClouds917
 * Date 2018/2/7
 * Description:文件上传
 */
@RestController
public class UploadController {
    /**
     * 文件上传
     * @param file
     */
    @PostMapping("/uploadBlog")
    public Map<String,Object> uploadBlog(MultipartFile file){
        Map<String,Object> map = new HashMap<String, Object>();
        System.out.println("============>文件上传");
        System.out.println(file);
        try {

            if(null != file){
                String filename = file.getOriginalFilename();
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = AliyunOSSUtil.upload(newFile);
                    System.out.println(uploadUrl);
                    map.put("status",0);
                    map.put("imgUrl",uploadUrl);
                }

            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return map;
    }

    @PostMapping("/deleteFile")
    public Map<String,Object> deleteFile(@RequestParam String file){
        Map<String,Object> map = new HashMap<String, Object>();
        try {
            String uploadUrl = AliyunOSSUtil.deleteFile(file);
            map.put("status",0);
            map.put("msg","删除成功！");
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return map;
    }



    @RequestMapping(value = "toUploadBlog",method = RequestMethod.GET)
    public String toUploadBlog(){
        return "upload";
    }

}

